package cn.tedu.imop.emqx.service;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * EMQX的消息中间的消费者
 * 订单服务用来接收(订阅 subscribe)设备发送的消息
 * 1 订阅topic
 * 4个方法里,哪个放个来订阅topic 比较合理 连接成功 connectComplete 订阅topic
 * 2 接收到消息
 */
public class MqttConsumer implements MqttCallbackExtended {
    private static final Logger log = LoggerFactory.getLogger(MqttConsumer.class);
    private MqttClient mqttClient;
    /**
     * 通过构造器设置
     * @param mqttClient
     */
    public MqttConsumer(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.debug("MqttConsumer#connectComplete方法被调用了,表示连接成功," +
                "reconnect:{},serverURI:{}",reconnect,serverURI);
        try {
            log.debug("连接成功,订阅开始充电指令的响应topic:{}","test/order");
            mqttClient.subscribe("test/order");
            log.debug("连接成功,订阅开始充电指令的响应topic:{},成功.","test/order");
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void connectionLost(Throwable cause) {
        log.debug("MqttConsumer#connectionLost方法被调用了,表示连接丢失",cause);
    }
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.debug("MqttConsumer#messageArrived方法被调用了,表示消息到达," +
                "topic:{},message:{}",topic,message);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.debug("MqttConsumer#deliveryComplete方法被调用了,表示消息分发完成" +
                "token:{}",token);
    }
}